<template>
	<view class="container">
		<!-- 餐厅信息 -->
		<view class="restaurant-header">
			<view class="header-content">
				<text class="name">{{ resInfo.name }}</text>
				<view class="meta-info">
					<view class="location">
						<uni-icons type="location-filled" size="16" color="#FF6B6B"></uni-icons>
						<text>{{ resInfo.location }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 就餐方式 -->
		<view class="dining-selector">
			<view class="dining-card" :class="{ active: diningType === 'dineIn' }" @click="diningType = 'dineIn'">
				<uni-icons type="shop" size="24" :color="diningType === 'dineIn' ? '#fff' : '#FF6B6B'"></uni-icons>
				<text>堂食</text>
			</view>
			<view class="dining-card" :class="{ active: diningType === 'takeaway' }" @click="diningType = 'takeaway'">
				<uni-icons type="cart" size="24" :color="diningType === 'takeaway' ? '#fff' : '#FF6B6B'"></uni-icons>
				<text>打包</text>
			</view>
		</view>

		<!-- 订单列表 -->
		<scroll-view class="order-list" scroll-y>
			<view v-for="(item, index) in cartlist" :key="index" class="order-item">
				<image class="food-image" :src="item.imageUrl || '/static/food-placeholder.png'" mode="aspectFill" />
				<view class="item-info">
					<view class="info-header">
						<text class="food-name">{{ item.name }}</text>
						<text class="food-price">¥{{ item.price * item.quantity }}</text>
					</view>
					<view class="item-meta">
						<text class="quantity">x{{ item.quantity }}</text>
						<text class="unit-price">单价: ¥{{ item.price }}</text>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="activity-selector">
			<picker mode="selector" :range="activities" range-key="name" @change="handleActivityChange">
				<view class="picker-content">
					<uni-icons type="flag" size="18" color="#666"></uni-icons>
					<text class="selected-text">
						{{ selectedActivity ? selectedActivity.name : '请选择参与的活动' }}
					</text>
					<uni-icons type="arrowdown" size="16" color="#999"></uni-icons>
				</view>
			</picker>
		</view>

		<!-- 备注输入 -->
		<view class="remark-box">
			<uni-icons type="compose" size="18" color="#666"></uni-icons>
			<input class="remark-input" v-model="remark" placeholder="请输入备注（口味、偏好等）" placeholder-class="placeholder" />
		</view>

		<!-- 支付方式 -->
		<view class="payment-selector">
			<view class="payment-option" :class="{ active: paymentMethod === 'campusCard' }"
				@click="handlePaymentClick('campusCard')">
				<view class="radio">
					<view class="radio-inner" v-if="paymentMethod === 'campusCard'"></view>
				</view>
				<text>校园卡支付</text>
				<uni-icons type="card" size="18" color="#4CAF50"></uni-icons>
			</view>
			<view class="payment-option" :class="{ active: paymentMethod === 'wechatPay' }"
				@click="handlePaymentClick('wechatPay')">
				<view class="radio">
					<view class="radio-inner" v-if="paymentMethod === 'wechatPay'"></view>
				</view>
				<text>微信支付</text>
				<uni-icons type="weixin" size="18" color="#09BB07"></uni-icons>
			</view>
		</view>

		<!-- 底部操作栏 -->
		<view class="action-bar">
			<view class="price-info">
				<text class="label">应付金额:</text>
				<text class="price">¥{{ finalTotalPrice }}</text>
			</view>
			<view class="pay-button" @click="showPaymentConfirm">
				<text>立即支付</text>
			</view>
		</view>
	</view>
</template>


<script setup>
	import {
		ref,
		computed,
		toRaw,
		onMounted,
		onUnmounted
	} from 'vue';
	import {
		useCartStore
	} from '../../stores/cart';
	import {
		pay,
		submitOrder,
		queryActivities
	} from '../../request/api.js'
	import {
		useUserStore
	} from '../../stores/user.js'

	const cartStore = useCartStore();
	const cartlist = ref(cartStore.cartlist);
	const resInfo = ref(cartStore.restaurant);
	const socket = ref(null);
	// 就餐方式
	const diningType = ref('dineIn');
	// 备注信息
	const remark = ref('');
	// 支付方式，默认选中校园卡支付
	const paymentMethod = ref('campusCard');

	const activities = ref([])

	const selectedActivity = ref({
		id: 0,
		name: '不参与活动'
	})

	const restaurantId = cartStore.restaurant.id
	// 处理活动选择
	const handleActivityChange = (e) => {
		const index = e.detail.value
		selectedActivity.value = index >= 0 ? activities.value[index] : null
		const condition = selectedActivity.value.condition_amount;
		if (condition && Number(condition) <= finalTotalPrice) {

		}
	}

	// 修改最终价格计算
	const finalTotalPrice = computed(() => {
		let total = cartStore.totalPrice

		// 打包费
		if (diningType.value === 'takeaway') total += 1

		// 活动优惠
		if (!selectedActivity.value?.condition_amount || (selectedActivity.value?.condition_amount && Number(
				selectedActivity.value.condition_amount) <= total)) {
			if (selectedActivity.value.discount_amount) total -= Number(selectedActivity.value.discount_amount)
			else if (selectedActivity.value.discount_percent) total = total * Number(selectedActivity.value
				.discount_percent) / 100
		}

		return Math.max(total, 0) // 保证最低0元
	})

	// 处理支付方式点击事件
	const handlePaymentClick = (method) => {
		if (paymentMethod.value !== method) {
			paymentMethod.value = method;
		}
	};

	// 显示支付确认弹窗
	const showPaymentConfirm = () => {
		uni.showModal({
			title: '确认支付',
			content: `您需要支付 ${finalTotalPrice.value} 元`,
			confirmText: '确认支付',
			cancelText: '取消支付',
			success: async (res) => {
				if (res.confirm) {
					console.log('用户点击确认支付');
					// 这里调用后端接口，你可以自行补充具体逻辑
					// 示例：调用后端接口的函数，比如 payOrder()
					// payOrder();
					const res = await pay(finalTotalPrice.value);
					if (res.message === 'Balance deducted successfully') {
						const param = {
							orderTime: new Date(),
							restaurant: cartStore.restaurant,
							items: cartStore.cartlist,
							totalPrice: finalTotalPrice.value,
							remark: remark.value,
							activities: selectedActivity.value
						}
						const submitRes = await submitOrder(param);
						sendMessage(JSON.stringify(param));
						simulatePaymentSuccess();
					} else if (res.message === 'Insufficient balance') {
						showInsufficientBalanceAlert();
					}
					console.log(res, 'payRes')
				} else if (res.cancel) {
					console.log('用户点击取消支付');
				}
			}
		});
	};

	// 显示余额不足提示框
	const showInsufficientBalanceAlert = () => {
		uni.showModal({
			title: '余额不足',
			content: '您的余额不足以支付该订单，是否去充值？',
			confirmText: '去充值',
			cancelText: '退出',
			success: (res) => {
				if (res.confirm) {
					console.log('用户选择去充值');
					// 这里可以添加跳转到充值页面的逻辑
				} else if (res.cancel) {
					console.log('用户选择退出');
				}
			}
		});
	};

	// 模拟支付成功
	const simulatePaymentSuccess = () => {

		uni.showModal({
			title: '支付成功',
			content: '您的支付已成功，是否跳转到取餐界面？',
			confirmText: '跳转',
			cancelText: '取消',
			success: (res) => {
				if (res.confirm) {
					uni.switchTab({
						url: '/pages/order/index'
					});
				} else if (res.cancel) {
					console.log('用户选择不跳转');
				}
			}
		});
	};

	function sendMessage(data) {
		if (socket.value) {
			// 发送消息
			socket.value.send({
				data,
				success: () => {
					console.log('消息发送成功');
				},
				fail: (err) => {
					console.error('消息发送失败', err);
				}
			});
		}
	}

	function close() {
		if (socket.value) {
			// 关闭 WebSocket 连接
			socket.value.close({
				success: () => {
					console.log('WebSocket 关闭成功');
				},
				fail: (err) => {
					console.error('WebSocket 关闭失败', err);
				}
			});
		}
	}

	onMounted(async () => {
		console.log(cartStore.restaurant , 'res')
		const res = await queryActivities(restaurantId)
		console.log(res)
		activities.value = [...res.activities, {
			id: 0,
			name: '不参与活动',
			type: 'NULL'

		}]
		socket.value = uni.connectSocket({
			url: `ws://175.178.118.46:3000?restaurant_id=${restaurantId}`,
			success: () => {
				console.log('WebSocket 连接成功');
			},
			fail: (err) => {
				console.error('WebSocket 连接失败', err);
			}
		});

		// 监听连接成功事件
		socket.value.onOpen(() => {
			console.log('WebSocket 已打开');
		});

		// 监听接收到的消息
		socket.value.onMessage((res) => {
			// this.message.push(res.data);
			console.log('收到消息:', res.data);
		});

		// 监听连接关闭事件
		socket.value.onClose(() => {
			console.log('WebSocket 已关闭');
		});

		// 监听连接错误事件
		socket.value.onError((err) => {
			console.error('WebSocket 连接错误', err);
		});
	});

	onUnmounted(() => {
		if (socket.value) {
			socket.value.close();
		}
	});
</script>

<style scoped>
	/* 颜色变量 */
	:root {
		--primary: #FF6B6B;
		--secondary: #6B8EFF;
		--text-primary: #333;
		--text-secondary: #666;
		--border-color: #eee;
		--bg-color: #f8f9fa;
	}

	.container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background: var(--bg-color);
		padding-bottom: 88px;
	}

	/* 餐厅信息 */
	.restaurant-header {
		padding: 20px;
		background: #fff;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
	}

	.header-content .name {
		font-size: 24px;
		font-weight: 600;
		color: var(--text-primary);
		margin-bottom: 8px;
	}

	.meta-info {
		display: flex;
		align-items: center;
		gap: 12px;
	}

	.location {
		display: flex;
		align-items: center;
		font-size: 14px;
		color: var(--text-secondary);
	}

	/* 就餐方式选择 */
	.dining-selector {
		display: flex;
		gap: 16px;
		padding: 16px;
	}

	.dining-card {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 16px;
		border: 1px solid var(--border-color);
		border-radius: 12px;
		background: #fff;
		transition: all 0.2s;
	}

	.dining-card.active {
		background: var(--primary);
		border-color: var(--primary);
		color: #fff;
		transform: translateY(-2px);
		box-shadow: 0 4px 12px rgba(255, 107, 107, 0.2);
	}

	/* 订单列表 */
	.order-list {
		flex: 1;
		/* padding: 0 16px; */
	}

	.order-item {
		display: flex;
		background: #fff;
		border-radius: 12px;
		margin-bottom: 12px;
		padding: 12px;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03);
	}

	.food-image {
		width: 80px;
		height: 80px;
		border-radius: 8px;
		margin-right: 12px;
	}

	.item-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.info-header {
		display: flex;
		justify-content: space-between;
	}

	.food-name {
		font-size: 16px;
		font-weight: 500;
		color: var(--text-primary);
	}

	.food-price {
		font-size: 16px;
		color: var(--primary);
		font-weight: 600;
	}

	.item-meta {
		display: flex;
		justify-content: space-between;
		font-size: 14px;
		color: var(--text-secondary);
	}

	/* 备注输入 */
	.remark-box {
		display: flex;
		align-items: center;
		padding: 16px;
		margin: 16px;
		background: #fff;
		border-radius: 12px;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03);
	}

	.remark-input {
		flex: 1;
		margin-left: 8px;
		font-size: 14px;
		color: var(--text-primary);
	}

	.placeholder {
		color: #999;
	}

	/* 支付方式选择 */
	.payment-selector {
		padding: 0 16px;
	}

	.payment-option {
		display: flex;
		align-items: center;
		padding: 16px;
		margin-bottom: 8px;
		background: #fff;
		border-radius: 12px;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03);
	}

	.payment-option.active {
		border: 1px solid var(--primary);
	}

	.radio {
		width: 20px;
		height: 20px;
		border: 2px solid #ccc;
		border-radius: 50%;
		margin-right: 12px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.radio-inner {
		width: 12px;
		height: 12px;
		background: var(--primary);
		border-radius: 50%;
	}

	/* 底部操作栏 */
	.action-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 16px;
		background: #fff;
		box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
	}

	.price-info {
		display: flex;
		align-items: baseline;
	}

	.label {
		font-size: 14px;
		color: var(--text-secondary);
		margin-right: 8px;
	}

	.price {
		font-size: 24px;
		color: var(--primary);
		font-weight: 600;
	}

	.pay-button {
		background: linear-gradient(135deg, #FF6B6B 0%, #FF8E53 100%);
		color: #fff;
		padding: 12px 32px;
		border-radius: 30px;
		font-weight: 500;
		box-shadow: 0 4px 12px rgba(255, 107, 107, 0.2);
		transition: transform 0.1s;
	}

	.pay-button:active {
		transform: scale(0.95);
	}

	.activity-selector {
		margin: 16px 16px 0px 16px;
		background: #fff;
		border-radius: 12px;
		padding: 14px 16px;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03);
	}

	.picker-content {
		display: flex;
		align-items: center;
		gap: 8px;
	}

	.selected-text {
		flex: 1;
		font-size: 14px;
		color: #333;
	}

	.placeholder-text {
		color: #999;
	}
</style>